package com.eascs.web.demo.file;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.exception.RuntimeIOException;
import com.eascs.common.util.IoUtil;
import com.eascs.site.view.ViewContext;
import com.eascs.web.demo.view.DefaultMasterViewController;

@Controller
public class FileDemoAction extends DefaultMasterViewController {
	private final Logger logger = LoggerFactory.getLogger(FileDemoAction.class);

	@RequestMapping(value = "/demo/file/")
	public String index() {
		return "/sample/file/index";
	}

	@RequestMapping(value = "/demo/file/upload")
	public String upload(@RequestParam(value = "file", required = false) MultipartFile file) {
		logger.debug("name={},originalFilename={},size={},contextType={},", file.getName(), file.getOriginalFilename(), file.getSize(), file.getContentType());
		try {
			String uploadContext = IoUtil.text(file.getInputStream());
			ViewContext.put("uploadContext", uploadContext);
		} catch (IOException e) {
			throw new RuntimeIOException(e);
		}
		return "/sample/file/index";
	}

	@RequestMapping(value = "/demo/file/download")
	public void download(@RequestParam(value = "file") String file, HttpServletResponse httpServletResponse) {
		OutputStream os = null;
		try {
			File f = new File(file);
			logger.debug("file={},canonicalPath={},name={}", file, f.getCanonicalPath(), f.getName());
			if (!f.exists())
				throw new RuntimeIOException("file not found");
			os = httpServletResponse.getOutputStream();
			httpServletResponse.reset();
			httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + f.getName());
			httpServletResponse.setContentType("application/octet-stream; charset=utf-8");
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			IoUtil.fileToOutputStream(f, byteArrayOutputStream);
			os.write(byteArrayOutputStream.toByteArray());
			os.flush();
		} catch (IOException e) {
			throw new RuntimeIOException(e);
		} finally {
			IoUtil.close(os);
		}
	}

}
